import Table from "@/components/Table";
import { Space, Button, message, Modal, Form, Input, FormInstance, Tag } from "antd";
import '@/assets/styles/buttonStyles.css';
import '@/views/system/user/user.css';
import { DataType, ColumnsType } from "@/types/bikeDispatch";
import { useEffect, useState } from "react";
import { getCookie } from "@/utils/cookies";
import React from "react";
import 'react18-json-view/src/style.css'
import { useNavigate } from "react-router-dom";
import baseUrl from '@/config';
import LoadingIndicator from '@/components/loading';
import { Image } from 'antd';

const Dispatch: React.FC = () => {
  const [pageLoading, setPageLoading] = useState(true);
  const [data, setData] = useState<DataType[]>([]);
  const [form] = Form.useForm();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpenAdd, setIsModalOpenAdd] = useState(false);
  const [selInfo, setSelInfo] = useState('');
  const [listNum, setListNum] = useState(0);


  const showModalAdd = () => {
    setIsModalOpenAdd(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const handleCancelAdd = () => {
    setIsModalOpenAdd(false);
  };

  const navigateTo = useNavigate();
  useEffect(() => {
    // 判断是否有token，检测用户是否已登录，如果未登录，给出提示，并将其跳转到登录页
    if (getCookie('token') == null) {
      message.error("尚未登录，不得访问！", 1);
      navigateTo("/login");
      return;
    }
    fetchData(); // 调用获取数据的函数
  }, []);

  const fetchData = async () => {
    try {
      const response = await fetch(baseUrl + '/back/bikeDispatch/getBikeDispatchList', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        },
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.msg === '操作成功') {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const handleDispatch = (record: DataType, e?: React.MouseEvent<HTMLElement, MouseEvent>) => {
    if (e) {
      console.log('处理单车调度：', record);
      setIsModalOpen(true);
    }
  }

  const columns: ColumnsType<DataType> = [
    {
      title: "序号",
      dataIndex: "index",
      key: "index",
      render: (_, _record, index) => <span>{index + 1}</span>,
    },
    {
      title: "调度区域",
      dataIndex: "zoneName",
      key: "zoneName",
    },
    {
      title: "单车情况图",
      dataIndex: "dispatchImgUrl",
      key: "dispatchImgUrl",
      render: (text) => {
        return (
          <>
            <Image src={text} width={80} />
          </>
        );
      }
    },
    {
      title: "调度申请人",
      dataIndex: "dispatchApplier",
      key: "dispatchApplier",
    },
    {
      title: "申请处理人",
      dataIndex: "dispatchReceiver",
      key: "dispatchReceiver",
    },
    {
      title: "调度状态",
      dataIndex: "dispatchState",
      key: "dispatchState",
      render: (text) => {
        // 根据 text 的值分配不同的 Tag 样式
        if (text === '未处理') {
          return <Tag color="blue">{text}</Tag>;
        } else if (text === '已完成') {
          return <Tag color="green">{text}</Tag>;
        } else if (text === '已拒绝') {
          return <Tag color="red">{text}</Tag>;
        } else {
          // 如果 text 不匹配上述条件，则返回默认样式的 Tag
          return <Tag color="yellow">{text}</Tag>;
        }
      }
    },
    {
      title: "请求调度时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "最后处理时间",
      dataIndex: "updateTime",
      key: "updateTime",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          {record.dispatchState === "未处理" && (
            <Button className="edit-button" onClick={(e) => handleDispatch(record, e)}>处理调度</Button>
          )}
        </Space>
      ),
    },
    {
      title: "id",
      dataIndex: "id",
      key: "id",
      className: 'hiddenColumn'
    }
  ];

  const selInfoDetail = async () => {
    try {
      setPageLoading(true);
      const response = await fetch(baseUrl + '/back/bikeDispatch/getBackDispatchByNickNameBack?dispatchApplier=' + selInfo, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'token': `${getCookie('token')}`
        }
      });
      setPageLoading(false);
      if (response.ok) {
        // 请求成功
        const data = await response.json();
        // 处理响应数据
        if (data.code === 200) {
          const dataWithKeys = data.data.map((item: { id: { toString: () => any; }; }) => ({ ...item, key: item.id.toString() }));
          setData(dataWithKeys);
          setListNum(dataWithKeys.length);
          message.success(data.msg, 1);
        }
        else {
          message.warning(data.msg, 1);
        }
      } else {
        // 请求失败
        console.error('Error:', response.status);
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  const SubmitButton = ({ form }: { form: FormInstance }) => {
    const [submittable, setSubmittable] = React.useState(false);

    // Watch all values
    const values = Form.useWatch([], form);

    React.useEffect(() => {
      form.validateFields({ validateOnly: true }).then(
        () => {
          setSubmittable(true);
        },
        () => {
          setSubmittable(false);
        },
      );
    }, [values]);

    return (
      <Button type="primary" htmlType="submit" disabled={!submittable} onClick={selInfoDetail}>
        查询
      </Button>
    );
  };

  const handleSelInfoChange = (event: { target: { value: React.SetStateAction<string>; }; }) => {
    setSelInfo(event.target.value);
  };

  return (
    <>
      <LoadingIndicator loading={pageLoading} />
      <Form form={form} name="validateOnly" layout="inline" autoComplete="off">
        <Form.Item>
          <Button type="primary" className="add-button" onClick={showModalAdd}>
            新增
          </Button>
        </Form.Item>
        <Modal title="系统提示" open={isModalOpenAdd} okText="知道了"
          cancelText="取消" onOk={handleCancelAdd} onCancel={handleCancelAdd}>
          <p>单车调度为用户自行申请递交,为确保数据稳定,暂不支持新增调度！</p>
        </Modal>
        <Form.Item name="name" label="" rules={[{ required: true, message: "查找字段内容不得为空,如不想查找请点击重置!" }]}>
          <Input placeholder="(按申请人精确查询）" value={selInfo} onChange={handleSelInfoChange} />
        </Form.Item>
        <Form.Item>
          <Space>
            <SubmitButton form={form} />
            <Button htmlType="reset">重置</Button>
          </Space>
        </Form.Item>
        <Tag bordered={true} color="green" className="total-tag">
          共{listNum}条记录
        </Tag>
        <Button type="link" onClick={fetchData}>查询所有</Button>
      </Form>
      <Modal title="调度处理" open={isModalOpen} okText="知道了"
        cancelText="取消" onOk={handleCancel} onCancel={handleCancel}>
        <p>已通知相关调度人员去处理调度，并下发了相关指令！（尚在开发）</p>
      </Modal>
      <Table<DataType> columns={columns} dataSource={data} />
    </>
  );
};

export default Dispatch;